﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.ComponentModel;

namespace Lilium.UI.Forms
{
	public sealed class FormMenuAdapter : Component, IMenuAdapter
	{
		#region IMenuAdapter Members

		public void Clear()
		{
			EnsureBound();

			if (TrackItems)
			{
				foreach (var item in TrackedItems)
					MenuItem.MenuItems.Remove(item);
				TrackedItems.Clear();
			}
			else
				MenuItem.MenuItems.Clear();
		}

		public IMenuItemAdapter AddMenuItem(string text)
		{
			EnsureBound();

			var menuItem = new MenuItem()
			{
				Text = text,
			};
			MenuItem.MenuItems.Add(menuItem);
			if (TrackItems)
				TrackedItems.Add(menuItem);

			return new MenuItemAdapter(menuItem);
		}

		#endregion

		#region public MenuItem MenuItem

		private MenuItem m_MenuItem;

		public MenuItem MenuItem
		{
			[DebuggerNonUserCodeAttribute]
			get
			{
				return m_MenuItem;
			}
			[DebuggerNonUserCodeAttribute]
			set
			{
				m_MenuItem = value;
			}
		}

		#endregion

		#region public bool TrackItems

		[DefaultValue(true)]
		public bool TrackItems
		{
			[DebuggerNonUserCodeAttribute]
			get
			{
				return TrackedItems != null;
			}
			[DebuggerNonUserCodeAttribute]
			set
			{
				if (value != TrackItems)
				{
					if (value)
						TrackedItems = new List<MenuItem>();
					else
						TrackedItems = null;
				}
			}
		}

		#endregion

		private void EnsureBound()
		{
			if (MenuItem == null)
				throw new InvalidOperationException(string.Format(
					Resources.Culture,
					Resources.FormMenuAdapter_MenuItemUnbound));
		}

		#region private List<MenuItem> TrackedItems

		private List<MenuItem> m_TrackedItems;

		private List<MenuItem> TrackedItems
		{
			[DebuggerNonUserCodeAttribute]
			get
			{
				return m_TrackedItems;
			}
			set
			{
				m_TrackedItems = value;
			}
		}

		#endregion
	}
}